package com.example.consume;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <h1> 延时消费 <h1>
 *
 * @author 魏如元
 * @since 2022/7/6
 */
@Service
public class DelayConsumerService {

    @Value("${rocketmq.name-server}")
    private String nameServer;

    public void  delayConsumer(){
        try {
            // 实例化消费者
            final DefaultMQPushConsumer consumer = new DefaultMQPushConsumer();
            consumer.setConsumerGroup("delay-producer");
            consumer.setNamesrvAddr(nameServer);
            // 订阅Topics
            consumer.subscribe("broker-delay", "*");
            // 注册消息监听者
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

                    for (MessageExt msg : msgs) {
                        System.out.println("接收到的消息：[msgBody=" + new String(msg.getBody()) + "] "
                                + (System.currentTimeMillis() - msg.getBornTimestamp()) + "ms 以后");
                    }

                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });

            //启动消费者
            consumer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
